// 2025/10/20
// 填充每个结点的下一个右侧结点二

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        if(root == nullptr)
            return root;
        queue<pair<Node*, int>> q;
        q.emplace(root, 0);
        while(!q.empty())
        {
            auto cur = q.front();
            q.pop();
            if(!q.empty() && q.front().second == cur.second)
                cur.first->next = q.front().first;
            
            if(cur.first->left)
                q.emplace(cur.first->left, cur.second + 1);
            if(cur.first->right)
                q.emplace(cur.first->right, cur.second + 1);
        }
        return root;
    }
};